$(document).ready(
	function(){ 
		$('#consoleDlg')[0].style.display = "none";
		
		$("#gridTable").jqGrid({   
            url:getContextPath()+"/base/device/getAllDevices.do",   
            datatype: "json",// "local",
            height: 350,   
            colNames:['序号','监测类别','设备名称','设备类型', '设备指令', '双字序列', '位序列', '状态值', '状态描述', '可控', '报警级别'],
			colModel:[
				{name:'id', index:'id', width:70, align:"left", hidden: true},
				{name:'mTypeName', index:'mTypeName', width:100, align:"left"},
				{name:'deviceDisplayName', index:'deviceDisplayName', width:100, align:"left"},
		   		{name:'deviceType', index:'deviceType', width:80, align:"left"},
		   		{name:'instructionCode', index:'instructionCode', width:120, align:"left", sortable:false},
		   		{name:'dWordSeq', index:'dWordSeq', width:100, align:"left", sortable:false},
		   		{name:'bitSeq', index:'bitSeq', width:100, align:"left", sortable:false},
		   		{name:'statusValue', index:'statusValue', width:100, align:"left", sortable:false},
		   		{name:'statDesc', index:'statDesc', width:100, align:"left", sortable:false},
		   		{name:'controllFlag', index:'controllFlag', width:50, align:"left", sortable:false},
		   		{name:'alarmName', index:'alarmName', width:100, align:"left", sortable:false}
			],
            sortname:'id',   
            // sortorder:'asc',
            viewrecords:true, 
            pgtext : "页 {0} 共 {1}页",
            recordtext:'记录 {0} - {1} 总记录数 {2}',  
            emptyrecords : "无数据",
            loadtext : "获取数据中...",
            rowNum: 15,//10,   
            loadonce: true,
            //rowList:[10,20,30],   
            jsonReader: { 
				repeatitems:false,   	 // 设置成false，在后台设置值的时候，可以乱序。且并非每个值都得设
				root: "rows",               // 数据行（默认为：rows）   
				total: "total",        // 总记录数   
				page: "page",            // 当前页   
				records: "records"
                //root:"dataRows",        // 数据行（默认为：rows）
                //page: "pages",    // 当前页
                //total: "totals",  // 总页数
                //records: "records",  // 总记录数
                //repeatitems : false    
            }, 
            //prmNames : {
				//search : "search",
				//rows:"pageModel.rows",
				//page:"pageModel.page",
				// sort:"page.orderBy",
				// order:"page.order"
			//}, 
            pager:"#gridPager",  
            caption: "监测设备 "
		});  
		$("#gridTable").jqGrid('navGrid','#gridPager',{edit:false,add:false,del:false});
		
		// 配置对话框
		$("#consoleDlg").dialog( {
			autoOpen : false,
			modal : true, // 设置对话框为模态（modal）对话框
			resizable : true,
			width : 600,
			buttons : { // 为对话框添加按钮
				"取消" : function() {
					$("#consoleDlg").dialog("close")
				},
				"添加" : addInfo,
				"保存" : updateInfo,
				"删除" : deleteInfo
			}
		});  
		
		//初始化对话框中的MonitorType下拉框
		$.ajax({
			type: "POST",
			url : getContextPath()+"/base/monitorType/getAllMonitorTypesObj.do", 
			data : {},
			dataType : "json",
			async : false,
			cache: false,
			error : function(textStatus, errorThrown) {
				alert("系统ajax交互错误: " + textStatus);
			},
			success : function(data, textStatus) {
				if (data != null) {
					var roleSelect = $("#consoleDlg").find("#monitorType");
					for (var i=0; i<data.length; i++) {
						//ie8不支持
						//roleSelect.append(new Option(data[i].name, data[i].id));
						roleSelect.append('<option value="'+data[i].id+'">'+data[i].name+'</option>');
					}
				}
			}
		});
		
		//初始化对话框中的AlarmConfig下拉框
		$.ajax({
			type: "POST",
			url : getContextPath()+"/base/alarmConfig/getAllAlarmConfigsObj.do", 
			data : {},
			dataType : "json",
			async : false,
			cache: false,
			error : function(textStatus, errorThrown) {
				alert("系统ajax交互错误: " + textStatus);
			},
			success : function(data, textStatus) {
				if (data != null) {
					var roleSelect = $("#consoleDlg").find("#alarmConfig");
					for (var i=0; i<data.length; i++) {
						//ie8不支持
						//roleSelect.append(new Option(data[i].alarmName, data[i].id));
						roleSelect.append('<option value="'+data[i].id+'">'+data[i].alarmName+'</option>');
					}
				}
			}
		});
			
	}
)

		// getContextPath
		function getContextPath() {
    		var pathName = document.location.pathname;
    		var index = pathName.substr(1).indexOf("/");
    		var result = pathName.substr(0,index+1);
    		return result;
		};

		var openDialog4Adding = function() {  
			var consoleDlg = $("#consoleDlg");  
			var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");  
			consoleDlg.find("input").removeAttr("disabled").val(""); 
			consoleDlg.find("select").removeAttr("disabled").val("no");
			consoleDlg.find("textarea").val("").removeAttr("disabled");
			dialogButtonPanel.find("button:not(:contains('取消'))").hide();  
			dialogButtonPanel.find("button:contains('添加')").show();  
			consoleDlg.dialog("option", "title", "添加监测设备 ").dialog("open");  
		};  
		
		var openDialog4Updating = function() {
			var consoleDlg = $("#consoleDlg");  
	        var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");    
	        consoleDlg.find("input").val("").removeAttr("disabled"); 
	        consoleDlg.find("select").removeAttr("disabled");
	        consoleDlg.find("textarea").val("").removeAttr("disabled"); 
	        dialogButtonPanel.find("button:not(:contains('取消'))").hide();  
	        dialogButtonPanel.find("button:contains('保存')").show();  
	        consoleDlg.dialog("option", "title", "修改监测设备");  
	          
	        loadSelectedRowData();  
		};
		
		var openDialog4Deleting = function() {
			var consoleDlg = $("#consoleDlg");  
	        var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");         
	        consoleDlg.find("input").attr("disabled", true); 
	        consoleDlg.find("select").attr("disabled", true); 
	        consoleDlg.find("textarea").attr("disabled", true); 
	        dialogButtonPanel.find("button:not(:contains('取消'))").hide();  
	        dialogButtonPanel.find("button:contains('删除')").show();  
	        consoleDlg.dialog("option", "title", "删除监测设备");  
	          
	        loadSelectedRowData();  
		};
		
		var loadSelectedRowData = function() {
			var selectedRowId = $("#gridTable").jqGrid("getGridParam", "selrow");
	    	//alert("selectRowID:"+selectedRowId);
	    	if (!selectedRowId) {
	    		alert("请先选择需要编辑的行!");
	    		return false;
	    	} else {
	    		var params = {"eid" : selectedRowId};
	    		// 从Server读取对应ID的JSON数据
	    		$.ajax( {
	    			type:"POST",   
	    			url : getContextPath()+"/base/device/getDeviceByID.do",
	    			data : params,
	    			dataType : "json",
	    			//contentType: "application/json",
	    			cache : false,
	    			async:false,
	    			error : function(textStatus, errorThrown) {
						alert("系统ajax交互错误: " + textStatus.responseText);
					},
					success : function(data, textStatus) {
						// 如果读取结果成功，则将信息载入到对话框中     
						var rowData = data;
						var consoleDlg = $("#consoleDlg");

						consoleDlg.find("#selectId").val(rowData.id);
						//alert("hiddenID1:"+consoleDlg.find("#selectId").val());
						consoleDlg.find("#monitorType").val(rowData.monitorType.id);
						
						consoleDlg.find("#deviceType").val(rowData.deviceType);
						consoleDlg.find("#devicename").val(rowData.devicename);
						consoleDlg.find("#deviceDisplayName").val(rowData.deviceDisplayName);
						consoleDlg.find("#instructionCode").val(rowData.instructionCode);
						consoleDlg.find("#deviceImageUrl").val(rowData.deviceImageUrl);
						consoleDlg.find("#dWordSeq").val(rowData.dWordSeq);
						consoleDlg.find("#bitSeq").val(rowData.bitSeq);
						consoleDlg.find("#statusValue").val(rowData.statusValue);
						consoleDlg.find("#statDesc").val(rowData.statDesc);
						//consoleDlg.find("#controllFlag").val(rowData.controllFlag);
						if (rowData.controllFlag == "1")
							consoleDlg.find("#controllFlag").attr("checked", true)
						else
							consoleDlg.find("#controllFlag").attr("checked", false);
						consoleDlg.find("#statImageUrl").val(rowData.statImageUrl);
						consoleDlg.find("#alarmConfig").val(rowData.alarmConfig.id);
						consoleDlg.find("#alarmContent").val(rowData.alarmContent);
						consoleDlg.find("#remark").val(rowData.remark);
											
						// 根据新载入的数据将表格中的对应数据行一并更新一下
						var dataRow = {
								id : rowData.id, // 从Server端得到系统分配的id  
								mTypeName : rowData.monitorType.name,
								deviceDisplayName : rowData.rowData,
								deviceType : rowData.deviceType,
								instructionCode : rowData.instructionCode,
								dWordSeq : rowData.dWordSeq,
								bitSeq : rowData.bitSeq,
								statusValue : rowData.statusValue,
								statDesc : rowData.statDesc,
								controllFlag : (rowData.controllFlag=="1")?"是":"否",
								alarmName : rowData.alarmConfig.alarmName
						};

						$("#gridTable").jqGrid("setRowData", data.id, dataRow);

						// 打开对话框
						consoleDlg.dialog("open");
					}
	    		});
	    	}
		};
		
		var checkValid = function() {
	    	var consoleDlg = $("#consoleDlg");
	    	
	    	var mTypeID = $.trim(consoleDlg.find("#monitorType").val()); 
	    	if (mTypeID=="no") {
	    		alert("'监测类别'为必选信息");
	    		return false;
	    	}
	    	var deviceType = $.trim(consoleDlg.find("#deviceType").val());
	    	if (deviceType=="no") {
	    		alert("'设备类型'为必选信息");
	    		return false;
	    	}
			var devicename = $.trim(consoleDlg.find("#devicename").val());
			if (devicename=="") {
	    		alert("'设备名称'为必填信息");
	    		return false;
	    	}
			
			var deviceDisplayName = $.trim(consoleDlg.find("#deviceDisplayName").val());
			if (deviceDisplayName=="") {
	    		alert("'设备显示名称'为必填信息");
	    		return false;
	    	}
			
			var instructionCode = $.trim(consoleDlg.find("#instructionCode").val());
			if (instructionCode=="") {
	    		alert("'设备指令'为必填信息");
	    		return false;
	    	}
			
			var deviceImageUrl = $.trim(consoleDlg.find("#deviceImageUrl").val());
			if (deviceImageUrl=="") {
	    		alert("'设备图像路径'为必填信息");
	    		return false;
	    	}
	    }
		
		var addInfo = function() {
			var consoleDlg = $("#consoleDlg");

			if (checkValid()==false) return false;
						
			var mTypeID = $.trim(consoleDlg.find("#monitorType").val()); 
			var deviceType = $.trim(consoleDlg.find("#deviceType").val());
			var devicename = $.trim(consoleDlg.find("#devicename").val());
			var deviceDisplayName = $.trim(consoleDlg.find("#deviceDisplayName").val());
			var instructionCode = $.trim(consoleDlg.find("#instructionCode").val());
			var deviceImageUrl = $.trim(consoleDlg.find("#deviceImageUrl").val());
			var dWordSeq = $.trim(consoleDlg.find("#dWordSeq").val());
			var bitSeq = $.trim(consoleDlg.find("#bitSeq").val());
			var statusValue = $.trim(consoleDlg.find("#statusValue").val());
			var statDesc = $.trim(consoleDlg.find("#statDesc").val());
			if (consoleDlg.find("#controllFlag").attr("checked"))
				var controllFlag = "1"
			else
				var controllFlag = "0";
			var statImageUrl = $.trim(consoleDlg.find("#statImageUrl").val());
			var alarmConfigID = $.trim(consoleDlg.find("#alarmConfig").val());
			var alarmContent = $.trim(consoleDlg.find("#alarmContent").val());
			var remark = $.trim(consoleDlg.find("#remark").val());
			
			
			var params = {
					"mTypeID" : mTypeID,
					"deviceType" : deviceType,
					"devicename" : devicename,
					"deviceDisplayName" : deviceDisplayName,
					"instructionCode" : instructionCode ,
					"deviceImageUrl" : deviceImageUrl,
					"dWordSeq" : dWordSeq,
					"bitSeq" : bitSeq,
					"statusValue" : statusValue,
					"statDesc" : statDesc,
					"controllFlag" : controllFlag,
					"statImageUrl" : statImageUrl,
					"alarmConfigID" : alarmConfigID,
					"alarmContent" : alarmContent,
					"remark" : remark				
			};

			var actionUrl = getContextPath()+"/base/device/addDevice.do";

			$.ajax( {
					type: "POST",
					url : actionUrl,
					data : params,
					dataType : "json",
					cache : false,
					error : function(textStatus, errorThrown) {
						alert("系统ajax交互错误: " + textStatus);
					},
					success : function(data, textStatus) {
						if (data != null) {
							var dataRow = {
									id : data.id, // 从Server端得到系统分配的id  
									mTypeName : data.monitorType.name,
									deviceDisplayName : data.deviceDisplayName,
									deviceType : data.deviceType,
									instructionCode : data.instructionCode,
									dWordSeq : data.dWordSeq,
									bitSeq : data.bitSeq,
									statusValue : data.statusValue,
									statDesc : data.statDesc,
									controllFlag : (data.controllFlag=="1")?"是":"否",
									alarmName : data.alarmConfig.alarmName
							};

							var srcrowid = $("#gridTable").jqGrid("getGridParam",
									"selrow");

							if (srcrowid) {
								$("#gridTable").jqGrid("addRowData",
										data.id, dataRow, "before",
										srcrowid);

							} else {
								$("#gridTable").jqGrid("addRowData",
										data.id, dataRow, "first");
							}
							consoleDlg.dialog("close");

							alert("监测设备添加操作成功!");

						} else {
							alert("[监测类别、设备名称]重复，添加操作失败!");
						}
					}
				});  
		};
		
		var updateInfo = function() {
			var consoleDlg = $("#consoleDlg");

			if (checkValid()==false) return false;
			
			var id = $.trim(consoleDlg.find("#selectId").val()); 
			var mTypeID = $.trim(consoleDlg.find("#monitorType").val()); 
			var deviceType = $.trim(consoleDlg.find("#deviceType").val());
			var devicename = $.trim(consoleDlg.find("#devicename").val());
			var deviceDisplayName = $.trim(consoleDlg.find("#deviceDisplayName").val());
			var instructionCode = $.trim(consoleDlg.find("#instructionCode").val());
			var deviceImageUrl = $.trim(consoleDlg.find("#deviceImageUrl").val());
			var dWordSeq = $.trim(consoleDlg.find("#dWordSeq").val());
			var bitSeq = $.trim(consoleDlg.find("#bitSeq").val());
			var statusValue = $.trim(consoleDlg.find("#statusValue").val());
			var statDesc = $.trim(consoleDlg.find("#statDesc").val());
			if (consoleDlg.find("#controllFlag").attr("checked"))
				var controllFlag = "1"
			else
				var controllFlag = "0";
			var statImageUrl = $.trim(consoleDlg.find("#statImageUrl").val());
			var alarmConfigID = $.trim(consoleDlg.find("#alarmConfig").val());
			var alarmContent = $.trim(consoleDlg.find("#alarmContent").val());
			var remark = $.trim(consoleDlg.find("#remark").val());
			
			var params = {
					"id" : id,
					"mTypeID" : mTypeID,
					"deviceType" : deviceType,
					"devicename" : devicename,
					"deviceDisplayName" : deviceDisplayName,
					"instructionCode" : instructionCode ,
					"deviceImageUrl" : deviceImageUrl,
					"dWordSeq" : dWordSeq,
					"bitSeq" : bitSeq,
					"statusValue" : statusValue,
					"statDesc" : statDesc,
					"controllFlag" : controllFlag,
					"statImageUrl" : statImageUrl,
					"alarmConfigID" : alarmConfigID,
					"alarmContent" : alarmContent,
					"remark" : remark				
			};
			var actionUrl = getContextPath()+"/base/device/updateDevice.do";

			$.ajax( {
				type : "POST",
				url : actionUrl,
				data : params,
				dataType : "json",
				cache : false,
				error : function(textStatus, errorThrown) {
					alert("系统ajax交互错误: " + textStatus);
				},
				success : function(data, textStatus) {
					if (data != null) {
						var dataRow = {
								id : data.id, // 从Server端得到系统分配的id  
								mTypeName : data.monitorType.name,
								deviceDisplayName : data.deviceDisplayName,
								deviceType : data.deviceType,
								instructionCode : data.instructionCode,
								dWordSeq : data.dWordSeq,
								bitSeq : data.bitSeq,
								statusValue : data.statusValue,
								statDesc : data.statDesc,
								controllFlag : (data.controllFlag=="1")?"是":"否",
								alarmName : data.alarmConfig.alarmName
						};
						alert("监测设备更新成功!");
						consoleDlg.dialog("close");
						$("#gridTable").jqGrid("setRowData", data.id, dataRow);
					} else {
						alert("[监测类别、设备名称]重复，修改操作失败!");
					}
				}
			});
		};
		
		var deleteInfo = function() {
			var consoleDlg = $("#consoleDlg");  
			
			var r=confirm("确认要删除该信息吗？");
			if (r==false) {
				consoleDlg.dialog("close"); 
				return false;
			}
	        
			var pId = $.trim(consoleDlg.find("#selectId").val());
	        var params = {"eID" : pId};  
	        var actionUrl = getContextPath() + "/base/device/deleteDevice.do";
	        $.ajax({  
	        	type : "POST",
	            url : actionUrl,  
	            data : params,  
	            //dataType : "json",  
	            cache : false,  
	            error : function(textStatus, errorThrown) {  
	                alert("系统ajax交互错误: " + textStatus);  
	            },  
	            success : function(data, textStatus) {  
	                if (data == "success") {  
	                    $("#gridTable").jqGrid("delRowData", pId);  
	                    consoleDlg.dialog("close");  
	                    alert("监测设备删除成功!");  
	                } else {  
	                    alert("删除操作失败!");  
	                }  
	            }  
	        });  
		};